import { query } from '../config/db.js';
import logger from '../config/logger.js';

/**
 * 获取所有学生
 */
const getStudents = async (req, res) => {
  try {
    const result = await query('SELECT * FROM students');

    res.json({
      students: result.rows
    });
  } catch (error) {
    logger.error('获取学生列表错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 根据ID获取学生
 */
const getStudentById = async (req, res) => {
  try {
    const { id } = req.params;

    const result = await query('SELECT * FROM students WHERE id = ?', [id]);

    if (result.rows.length === 0) {
      return res.status(404).json({
        message: '学生不存在'
      });
    }

    res.json({
      student: result.rows[0]
    });
  } catch (error) {
    logger.error('根据ID获取学生错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 创建新学生
 */
const createStudent = async (req, res) => {
  try {
    const { name, student_id, class_name, age, gender } = req.body;

    // 检查学生是否已存在
    const existingStudent = await query('SELECT * FROM students WHERE student_id = ?', [student_id]);

    if (existingStudent.rows.length > 0) {
      return res.status(400).json({
        message: '学生ID已存在'
      });
    }

    // 创建新学生
    await query(
      'INSERT INTO students (name, student_id, class_name, age, gender) VALUES (?, ?, ?, ?, ?)',
      [name, student_id, class_name, age, gender]
    );

    // 获取创建的学生
    const selectResult = await query(
      'SELECT * FROM students WHERE student_id = ?',
      [student_id]
    );

    logger.info(`学生创建: ${selectResult.rows[0].name} (ID: ${selectResult.rows[0].student_id})`);

    res.status(201).json({
      message: '学生创建成功',
      student: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('创建学生错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 更新学生
 */
const updateStudent = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, student_id, class_name, age, gender } = req.body;

    // 检查学生是否存在
    const existingStudent = await query('SELECT * FROM students WHERE id = ?', [id]);

    if (existingStudent.rows.length === 0) {
      return res.status(404).json({
        message: '学生不存在'
      });
    }

    // 检查新学生ID是否已存在
    if (student_id && student_id !== existingStudent.rows[0].student_id) {
      const idExists = await query('SELECT * FROM students WHERE student_id = ?', [student_id]);

      if (idExists.rows.length > 0) {
        return res.status(400).json({
          message: '学生ID已存在'
        });
      }
    }

    // 准备更新字段
    const updateFields = [];
    const params = [];

    if (name) {
      updateFields.push('name = ?');
      params.push(name);
    }

    if (student_id) {
      updateFields.push('student_id = ?');
      params.push(student_id);
    }

    if (class_name) {
      updateFields.push('class_name = ?');
      params.push(class_name);
    }

    if (age) {
      updateFields.push('age = ?');
      params.push(age);
    }

    if (gender) {
      updateFields.push('gender = ?');
      params.push(gender);
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    params.push(id);

    // 更新学生
    await query(
      `UPDATE students SET ${updateFields.join(', ')} WHERE id = ?`,
      params
    );

    // 获取更新后的学生
    const selectResult = await query(
      'SELECT * FROM students WHERE id = ?',
      [id]
    );

    logger.info(`学生更新: ${selectResult.rows[0].name} (ID: ${selectResult.rows[0].student_id})`);

    res.json({
      message: '学生更新成功',
      student: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('更新学生错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 删除学生
 */
const deleteStudent = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查学生是否存在
    const existingStudent = await query('SELECT * FROM students WHERE id = ?', [id]);

    if (existingStudent.rows.length === 0) {
      return res.status(404).json({
        message: '学生不存在'
      });
    }

    // 删除学生
    await query('DELETE FROM students WHERE id = ?', [id]);

    logger.info(`学生删除: ${existingStudent.rows[0].name} (ID: ${existingStudent.rows[0].student_id})`);

    res.json({
      message: '学生删除成功'
    });
  } catch (error) {
    logger.error('删除学生错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

export {
  getStudents,
  getStudentById,
  createStudent,
  updateStudent,
  deleteStudent
};